package com.qiankan.qmsj.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.google.gson.Gson;
import com.qiankan.qmsj.JDQBApplication;
import com.qiankan.qmsj.UserInfo;


/**
 * 用户信息数据库
 */
public class UserDBHelper {
    private static final String DATABASE_NAME = "jdqb.db";
    private static final String TABLE_NAME = "USERINFO";
    private static final int DATABASE_VERSION = 1;
    private static final String CREAT_TABLE_SQL = "CREATE TABLE IF NOT EXISTS "
            + TABLE_NAME + " ( 'ACCOUNT' TEXT, 'JSON' TEXT );";
    private static final String UPDATE_TABLE_SQL = "DROP TABLE IF EXISTS "
            + TABLE_NAME + ";";

    private static UserDBHelper mDBInstance;
    private Context mContext;
    private SQLiteDatabase mUserDB;

    /**
     * 获取用户登录信息
     *
     * @return 为null则需要登录
     */
    public UserInfo getUserInfo() {
        if (JDQBApplication.mLoginInfo == null) {
            Cursor cur = mUserDB.query(TABLE_NAME, new String[]{"ACCOUNT",
                    "JSON"}, null, null, null, null, null);
            for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                String json = cur.getString(1);
                JDQBApplication.mLoginInfo = new Gson().fromJson(json,
                        UserInfo.class);
            }
            cur.close();
        }
        return JDQBApplication.mLoginInfo;
    }

    /**
     * 保存用户登录信息
     *
     * @param loginInfo
     */
    public void saveUserInfo(UserInfo loginInfo) {
        if (loginInfo == null)
            return;
        mUserDB.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("ACCOUNT", loginInfo.getId());
            cv.put("JSON", loginInfo.toString());

            if (checkUserInfoExist(loginInfo)) {
                mUserDB.update(TABLE_NAME, cv, "account=?",
                        new String[]{loginInfo.getId()});
            } else {
                mUserDB.insert(TABLE_NAME, null, cv);
            }
            mUserDB.setTransactionSuccessful();
        } finally {
            mUserDB.endTransaction();
        }
        JDQBApplication.mLoginInfo = loginInfo;
    }

    /**
     * 用户退出
     */
    public void logoutUserInfo() {
        mUserDB.beginTransaction();
        try {
            mUserDB.delete(TABLE_NAME, null, null);
            mUserDB.setTransactionSuccessful();
        } finally {
            mUserDB.endTransaction();
        }
        JDQBApplication.mLoginInfo = null;
    }

    /**
     * 检查用户信息是否存在
     *
     * @param loginInfo
     * @return
     */
    private boolean checkUserInfoExist(UserInfo loginInfo) {
        int ret = mUserDB.query(TABLE_NAME, null, "account=?",
                new String[]{loginInfo.getId()}, null, null, null)
                .getCount();
        return ret > 0 ? true : false;
    }

    private UserDBHelper(Context applicationContext) {
        mContext = applicationContext;
    }

    public synchronized static UserDBHelper getInstance(Context context) {
        if (mDBInstance == null) {
            mDBInstance = new UserDBHelper(context.getApplicationContext());
            mDBInstance.open();
        }
        return mDBInstance;
    }

    private void open() {
        if (mUserDB == null || !mUserDB.isOpen()) {
            UserSQLiteOpenHelper uso = new UserSQLiteOpenHelper();
            mUserDB = uso.getWritableDatabase();
        }
    }

    class UserSQLiteOpenHelper extends SQLiteOpenHelper {

        public UserSQLiteOpenHelper() {
            super(mContext, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREAT_TABLE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(UPDATE_TABLE_SQL);
            onCreate(db);
        }
    }
}
